package com.inspur.edp.ai.flow.node;

import com.inspur.edp.ai.flow.engine.FlowContext;
import com.inspur.edp.ai.flow.engine.strategy.BranchFlowStrategy;
import com.inspur.edp.ai.flow.metadata.AbsNode;
import com.inspur.edp.ai.flow.spi.NodeExecuteResult;
import com.inspur.edp.ai.flow.spi.NodeExecutor;
import com.inspur.edp.common.expr.evaluator.ExpressEvaluator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lizhaorui
 * @date 2025/8/15
 * @description
 */

public class SelectorNodeExecutor implements NodeExecutor {

    @Override
    public String getKind() {
        return SelectorNode.KIND;
    }

    @Override
    public NodeExecuteResult execute(FlowContext context, AbsNode node, Map<String, Object> args) {
        SelectorNode selectorNode = (SelectorNode) node;
        String executePort = null;
        List<String> ignorePorts = new ArrayList<>();
        for (SelectorNode.SelectorBranch branch : selectorNode.getBranches()) {
            if (executePort == null) {
                ExpressEvaluator expressEvaluator = branch.getConditionEvaluator();
                if (expressEvaluator != null) {
                    boolean result = (boolean) expressEvaluator.evaluate(args);
                    if (result) {
                        executePort = branch.getPort();
                    } else {
                        ignorePorts.add(branch.getPort());
                    }
                } else {
                    executePort = branch.getPort();
                }
            } else {
                ignorePorts.add(branch.getPort());
            }
        }
        BranchFlowStrategy branchFlowStrategy = new BranchFlowStrategy();
        branchFlowStrategy.setBranchPortId(executePort);
        branchFlowStrategy.setIgnorePortIds(ignorePorts);
        branchFlowStrategy.setNodeId(node.getId());

        NodeExecuteResult nodeExecuteResult = new NodeExecuteResult();
        nodeExecuteResult.setFlowStrategy(branchFlowStrategy);
        return nodeExecuteResult;
    }

}